<?php

namespace App\Events\CollectPackage;

use App\Consts\GlobalConst;
use App\Consts\GlobalCounterConst;
use App\Models\UserCollectPackage;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class CreateCollectPackageEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    protected $channel = 'channel-event';

    /**
     * 收藏夹信息
     * @var UserCollectPackage $collectPackage
     */
    public $collectPackage;

    /**
     * 记录【统计日志】所需数据
     * @var array $logCountLoadData
     */
    public $logCountLoadData;

    public function __construct($collectPackage)
    {
        $this->collectPackage = $collectPackage;

        $this->logCountLoadData = [
            'send_user_id' => $collectPackage['user_id'],
            'receive_user_id' => $collectPackage['user_id'],
            'action_id' => $collectPackage['collect_package_id'],
            'action_type' => GlobalCounterConst::ACTION_TYPE_COLLECT_PACKAGE,
            'target_id' => $collectPackage['collect_package_id'],
            'target_type' => GlobalConst::TARGET_TYPE_FAVORITES,
            'created_at' => time(),
        ];
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel($this->channel);
    }

    /**
     * Execute the event.
     *
     * @return bool
     */
    public function handle()
    {
        Log::channel('event')->info(__CLASS__ . ' handle : ' . json_encode([
                'collect_package' => $this->collectPackage,
                'log_count' => $this->logCountLoadData
            ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));

        return true;
    }
}
